#!/bin/sh

# 显示关键信息
showMessage() {
    echo -e "\033[35m$1\033[0m"
}

# 显示警告信息
showWarning() {
    echo -e "\033[36m$1\033[0m"
}

# 切换目录位置
changeDirectory() {
    RUN_NAME=""
    case $0 in
        /*)
            RUN_NAME="$0"
            ;;
        *)
            PWD=`pwd`
            RUN_NAME="$PWD/$0"
            RUN_NAME=`echo $RUN_NAME|sed 's/\/\.//g'`
            ;;
    esac
    cd "`dirname $RUN_NAME`" 
}

changeDirectory

# 获取进程ID
getPid() {
    pid=`ps -ef|grep java|grep "$RUN_NAME"|awk '{print $2}'`
}

# 启动进程
start() {
    showMessage "Starting $RUN_NAME..."
    getPid
    if [ "X$pid" = "X" ]
    then
        # source JDK jdk1.8.0_66
        JAVA_HOME="/opt/soft/jdk/jdk1.8.0_162/"
        MAIN_CLASS="com.nx.arch.cloud.ApplicationMain"
        JAVA_OPTS="-D$RUN_NAME -server -Dconfig_path=config -Ddata_path=data -Dkey_namespace=featureupdater -Dtarget_sinks=$1 -Dsource_files=$2"

        CLASSPATH=.:./config
        for i in ./lib/*.jar ; do
            CLASSPATH=$CLASSPATH:$i
        done

        export CLASSPATH

        nohup $JAVA_HOME/bin/java $JAVA_OPTS $MAIN_CLASS &
    else
        showWarning "Failed to start $RUN_NAME, already running."
        return
    fi
    sleep 1
    getPid
    if [ "X$pid" = "X" ]
    then
        showWarning "Failed to start $RUN_NAME."
    else
        showMessage "Started $RUN_NAME."
    fi
}

# 关闭进程
stop() {
    showMessage "Stopping $RUN_NAME..."
    getPid
    if [ "X$pid" = "X" ]
    then
        showWarning "Failed to stop $RUN_NAME, not running."
        return
    else
        kill $pid
        if [ $? -ne 0 ]
        then
            showWarning "Unable to stop $RUN_NAME."
            return
        fi
    fi
    getPid
    CNT=0
    while [ "X$pid" != "X" ]
    do
        if [ "$CNT" -lt "5" ]
        then
            CNT=`expr $CNT + 1`
        else
            showMessage "Waiting for $RUN_NAME to exit..."
            CNT=0
        fi
        sleep 1
        getPid
    done
    if [ "X$pid" != "X" ]
    then
        showWarning "Failed to stop $RUN_NAME."
        return
    else
        showMessage "Stopped $RUN_NAME."
    fi
}

case "$1" in
    start)
        if [ "X$2" == "X" ] || [ "X$3" == "X" ]
        then
            showWarning "Usage: $0 start {sinks} {files} | $0 stop"
            exit 1
        fi
        start $2 $3
        ;;
    stop)
        stop
        ;;
    *)
        showWarning "Usage: $0 start {sinks} {files} | $0 stop"
        exit 1
esac
